﻿using System;
using System.IO;
using System.Net;
using LinqToLfsWorld.Interface;

namespace LinqToLfsWorld
{
	/// <summary>
	/// The response format to use when querying LFSWorld.
	/// </summary>
	internal enum PubstatResponseType : int
	{ 
		Json = 1, 
		PHPSerialized = 2,
		Xml = 3
	}

	/// <summary>
	/// Provides helper methods and properties for querying LFSWorld.
	/// </summary>
	internal class LfsHelper
	{

		/// <summary>
		/// Gets the pubstat URL base.
		/// </summary>
		/// <param name="responseType">Type of the response.</param>
		/// <param name="searchBase">The search base.</param>
		/// <param name="action">The action.</param>
		public static string GetPubstatUrlBase(PubstatResponseType responseType, ILfsWorldQuery searchBase, string action)
		{
			if(!(responseType == PubstatResponseType.Xml))
				throw new NotSupportedException("That response type is not currently supported: " + responseType.ToString());

			string url =  string.Format("http://www.lfsworld.net/pubstat/get_stat2.php?version=1.4&s={0}&action={1}",
				(int)responseType, action);

			if (searchBase.Context.PremiumPubstatAccess == true)
				url += "&ps=1";

			if (searchBase.Context.AuthenticationMode == AuthMode.IdentKey)
			{
				url += "&idk=" + searchBase.Context.IdentKey;
			}
			else
			{
				url += "&user=" + searchBase.Context.Username + "&pass=" + searchBase.Context.Password;
			}

			return url;
		}

		/// <summary>
		/// Gets the pubstat response from LfsWorld, given a url.
		/// </summary>
		/// <param name="url">The URL of the LfsWorld query.</param>
		public static string GetPubstatResponse(string url)
		{

			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			
			StreamReader reader = new StreamReader(response.GetResponseStream());
			string responseText = reader.ReadToEnd();

			reader.Dispose();

			return responseText;

		}

	}
}
